package android.money;

import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.money.data.Protocol;
import android.money.db.DBInfo;
import android.money.network.SyncConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Sync extends Activity implements OnClickListener{

	//First page's component
	private Button openConnectionButton;
	private TextView statusText;
	private String TXT_IDLE = "Idle";
	private String TXT_WAIT = "Waiting";
	public static final int SYNCS_SUCCESS = 0x001;
	public static final int SYNCS_FAIL = 0x002;
	private Thread syncConnection;
	public static SyncConnection syncRunnable;
	public static String threadName = "syncthread";
	private String phoneNumber = "";
	public Handler syncHandler =   new Handler(){
		//@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case Sync.SYNCS_SUCCESS:
				//Toast.makeText(Sync.this, "HARRAY", Toast.LENGTH_SHORT).show();
				Intent i = new Intent(Sync.this, TransactionConfirm.class);
				Map<String,String> paymentDetail = (Map<String,String>)msg.obj;
				i.putExtra(DBInfo.trans_amount, paymentDetail.get(Protocol.PAY_AMOUNT));
				i.putExtra(DBInfo.trans_unit, paymentDetail.get(Protocol.PAY_UNIT));
				i.putExtra(DBInfo.trans_reader, syncRunnable.getAddress());
				startActivity(i);
				finish();
				break;

			case SYNCS_FAIL:
				Toast.makeText(Sync.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
				openConnectionButton.setEnabled(true);
				openConnectionButton.setFocusable(true);
				statusText.setText(TXT_IDLE);
				break;
			}
			super.handleMessage(msg);

		}};
		protected void onCreate(Bundle icicle) {		
			super.onCreate(icicle);
			setContentView(R.layout.syn_page);
			phoneNumber = ((TelephonyManager)
			getSystemService(TELEPHONY_SERVICE)).getLine1Number();
			openConnectionButton = (Button)findViewById(R.id.openConnectionButton);
			statusText = (TextView)findViewById(R.id.statusText);
			statusText.setText(TXT_IDLE);
			openConnectionButton.setOnClickListener(this);
		}
		public String getHost(){
			String host = ((EditText)findViewById(R.id.posHost)).getText().toString();
			return host;
		}
		public void onClick(View arg0) {
			openConnectionButton.setEnabled(false);
			syncRunnable = new SyncConnection(this ,phoneNumber);
			syncConnection = new Thread(syncRunnable);
			syncConnection.start();
			statusText.setText(TXT_WAIT);

		}
		
}
